package main.java.cn.wolfcode.web.controller;

import cn.wolfcode.domain.Department;
import cn.wolfcode.domain.Permission;
import cn.wolfcode.domain.Role;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.IDepartmentService;
import cn.wolfcode.service.IPermissionService;
import cn.wolfcode.service.IRoleService;
import cn.wolfcode.util.RequiredPermission;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Controller
@RequestMapping("/role")
public class RoleContorler {
    @Autowired
    private IRoleService roleService;
    @Autowired
    private IPermissionService permissionService;
    @RequiredPermission(name = "角色页面", expression = "role:list")
    @RequestMapping("/list")
    public String list(Model model, @ModelAttribute("qo") QueryObject qo) {
        model.addAttribute("pageInfo", roleService.queryForList(qo));
        return "role/list";
    }

    @RequiredPermission(name = "角色新增/编辑", expression = "role:input")
    @RequestMapping("/input")
    public String input(Model model, Long id) {
        //共享查询所有的权限信息
        model.addAttribute("permissions", permissionService.selectAll());
        if (id != null) {
            //打开编辑页面,显示角色和权限的信息
            Role role = roleService.selectByPrimaryKey(id);
            model.addAttribute("role", role);
            List<Permission> permission= permissionService.selectByRloeId(role.getId());
            model.addAttribute("permission", permission);
        }
        return "role/input";
    }

    @RequiredPermission(name = "角色删除", expression = "role:delete")
    @RequestMapping("/delete")
    public String delete(Long id) {
        if (id != null) {
            roleService.deleteByPrimaryKey(id);
        }
        return "redirect:/role/list";
    }

    @RequiredPermission(name = "角色新增/编辑", expression = "role:saveOrUpdate")
    @RequestMapping("/saveOrUpdate")
    public String saveOrUpdate(Role role, Long[] ids) {

        if (role.getId() != null) {
            roleService.updateByPrimaryKey(role, ids);
        } else {
            roleService.insert(role, ids);
        }
        return "redirect:/role/list";
    }

}
